import time
from fastapi import Request, FastAPI
from starlette.middleware.base import BaseHTTPMiddleware
from backend.common.logging import logger

class HttpTimingMiddleware(BaseHTTPMiddleware): 
    async def dispatch(self, request: Request, call_next):
        start_time = time.time()
        response = await call_next(request)
        process_time = (time.time() - start_time) * 1000  # ms
        logger.info(f"{request.method} {request.url.path} - {process_time:.2f}ms")
        response.headers["X-Process-Time"] = str(f"{process_time:.2f}ms")
        return response

def register_http_timing_middleware(app: FastAPI):
    app.add_middleware(HttpTimingMiddleware) 